package com.shop.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 网关全局过滤器，来用拦截所有请求，同时可以定义白名单，黑名单，含有效token的放过
 * @date 2023/2/21 20:44
 */
@Order(-1)
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter {

    private static List<String> whiteList=null;

    //加载白名单
    static{
        //加载白名单
        try (
                InputStream resourceAsStream = MyGlobalFilter.class.getResourceAsStream("/white-list.properties");
        ) {
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            Set<String> strings = properties.stringPropertyNames();
            whiteList= new ArrayList<>(strings);

        } catch (Exception e) {
            log.error("加载‘white-list.properties白名单’出错:{}",e.getMessage());
            e.printStackTrace();
        }
    }

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();//访问路径
        log.info("本次访问路径为：{}",path);
        //白名单校验
        for (String whitePath : whiteList) {
            if (pathMatcher.match(whitePath,path)){
                log.info("该请求为白名单！");
                return chain.filter(exchange);
            }
        }

        try {
            //token校验（若token不存在也会报错捕获）
            String token = request.getHeaders().get("token").get(0);
            if (Strings.isEmpty(token)) {
                //token不存在
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                log.info("非白名单且不存在token");
                return exchange.getResponse().setComplete();
            }

            boolean tag = JwtUtils.checkToken(token);
            //判断token是否有效
            if (!tag){
                //token已过期
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                log.info("token过期或不合法");
                return exchange.getResponse().setComplete();
            }
        } catch (Exception e) {
            log.info("校验token异常，token有误");
            //token已过期
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //token有效，放行
        log.info("通过网关");
        return chain.filter(exchange);
    }
}
